package com.me.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.me.bbs.common.SessionUtils;
import com.me.bbs.dto.UserDTO;
import com.me.bbs.entity.User;
import com.me.bbs.entity.UserFollowing;
import com.me.bbs.mapper.UserMapper;
import com.me.bbs.service.IUserFollowingService;
import com.me.bbs.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lm
 * @since 2023-01-09
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    IUserFollowingService userFollowingService;

    @Override
    @Transactional
    public Page<UserDTO> getPage(Page<User> page, LambdaQueryWrapper<User> wrapper) {
        Long uid = (Long) SessionUtils.getAttribute("user");
        Page<User> userPage = this.page(page, wrapper);
        List<User> records = userPage.getRecords();
        List<UserDTO> userDTOS = new ArrayList<>(records.size());
        records.forEach(u -> {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(u, userDTO);
            if(uid == null)
                userDTO.setIsFollowed(false);
            else {
                boolean isFollowed = userFollowingService.lambdaQuery().eq(UserFollowing::getUser, uid)
                        .eq(UserFollowing::getFollowedUser, u.getUserId())
                        .exists();
                userDTO.setIsFollowed(isFollowed);
            }
            userDTOS.add(userDTO);
        });
        Page<UserDTO> dtoPage = new Page<>();
        BeanUtils.copyProperties(userPage, dtoPage);
        dtoPage.setRecords(userDTOS);
        return dtoPage;
    }
}
